package org.yege.algorithm.loadtest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * 并发压测线程类
 */
public class LoadThread implements Runnable{
    private List<TestResult> testResults;//测试结果集
    private String loadUrl;//测试url

    public LoadThread(List<TestResult> testResults, String loadUrl) {
        this.testResults = testResults;
        this.loadUrl = loadUrl;
    }

    public void run() {
        TestResult testResult=new TestResult();
        long startTime=System.currentTimeMillis();
        try {
            URL url = new URL(loadUrl);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection connection = (HttpURLConnection) urlConnection;
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while((current = in.readLine()) != null) {
                urlString += current;
            }

            testResult.setSuccess(true);
        }catch(IOException e) {
            testResult.setSuccess(false);
        }
        long endTime=System.currentTimeMillis();
        long cha=endTime-startTime;
        testResult.setFinishTime(cha);
        testResults.add(testResult);
        //System.out.println(testResult.toString());
    }

    public List<TestResult> getTestResults() {
        return testResults;
    }

    public void setTestResults(List<TestResult> testResults) {
        this.testResults = testResults;
    }

    public String getLoadUrl() {
        return loadUrl;
    }

    public void setLoadUrl(String loadUrl) {
        this.loadUrl = loadUrl;
    }
}
